<template>
	<view class="content">
		<!-- 轮播部分 -->
		<view class="uni-padding-wrap" style="padding-top: 10px;">
			<view class="page-section swiper"><bw-swiper :swiperList="bannerList" style="width:100%" :swiperType="true"></bw-swiper></view>
		</view>
		<!-- 选择模块 -->
		<view class="select_module">
			<view class="select_option" @tap="goRecord" v-show="userType == '监护人'">
				<view class="image_box"><image style="margin-left: 5px;" src="../../static/img/record-icon.png"></image></view>
				<view class="option_tip">Visit</view>
			</view>
			<view class="select_option" @tap="goSearch">
				<view class="image_box"><image src="../../static/img/search-icon.png"></image></view>
				<view class="option_tip">Find</view>
			</view>
			<view class="select_option" @tap="goLocation" v-if="userType != '学生'">
				<view class="image_box"><image src="../../static/img/address-icon.png"></image></view>
				<view class="option_tip">Location</view>
			</view>
			<view class="select_option" @tap="goPhone" v-if="userType == '学生'">
				<view class="image_box"><image src="../../static/img/telIcon.png"></image></view>
				<view class="option_tip">Call</view>
			</view>
			<view class="select_option" @tap="goFeedback" v-if="userType != '学生'">
				<view class="image_box" style="position: relative;">
					<!-- <image v-show="!isShowIcon" class="new_icon" src="../../static/img/newIcon.png"></image> -->
					<view v-show="!!tipNum" class="new_icon"></view>
					<image src="../../static/img/feedBack-icon.png"></image>
				</view>
				<view class="option_tip">Feedback</view>
			</view>
		</view>
		<view class="guardian_message">
			<view class="guardian_title">
				<!-- <text class="iconfont_icon">&#xe644;</text> -->
				<view class="line"></view>
				<text>{{ userType != '监护人' ? 'Guardian Information' : 'Next Visit Students Information' }}</text>
			</view>
			<view class="teacher_message" v-if="userType != '监护人'">
				<image class="teach_avatar" :src="!!avatar ? utils.localURL + '/' + avatar : txImg"></image>
				<view class="teach_box">
					<view class="teacher_name">
						<text>{{ gurdianInfo.userName || '' }}老师</text>
					</view>
					<text class="teacher_tel">Mobile：{{ gurdianInfo.guardianPhone || '' }}</text>
				</view>
			</view>
			<view class="uni-padding-wrap" v-else>
				<view class="page-section swiper">
					<view class="page-section-spacing">
						<swiper class="swiper" style="height: 110px;" :vertical="true" :autoplay="autoplay" interval="3000" :circular="true" :duration="duration">
							<!-- index < 3，最多只取数组内的前3个对象 -->
							<swiper-item class="swiper_item" :key="index" v-if="index < 3" v-for="(item, index) in recordList" @tap="goWriteRecord(item)">
								<image class="item_img" :src="!!item.stuPhotoPath ? utils.localURL + '/' + item.stuPhotoPath.replace(/\\/g, '/') : txImg" mode=""></image>
								<view class="item_name">
									<view>Student Name：{{ item.stuName }}</view>
									<view>Visit Date：{{ item.interviewDate }}</view>
								</view>
							</swiper-item>
						</swiper>
					</view>
				</view>
			</view>
		</view>
		<view class="today_message">
			<view class="today_title">
				<!-- <text class="iconfont_icon">&#xe644;</text> -->
				<view style="display: flex; align-items: center;">
					<view class="line"></view>
					<text style="font-size: 14px;">Announcement</text>
				</view>
				<text @tap="goProList" style="color: #999; font-size: 12px; width: 100px; text-align: right;">more</text>
			</view>
			<ul class="today_list">
				<li class="today_item" v-for="(item, index) in proclamationList" v-if="item.noticeDisplay == '是'" :key="index" @tap="goProDetails(item.noticeId)">
					<text style="width: 5px; height: 5px; border-radius: 50%; background-color: #9D9D9D; margin-right: 7px;"></text>
					<text class="item_text">{{ item.noticeTitle }}</text>
				</li>
			</ul>
		</view>
		<bar indexActive="0" :tabList="tabList"></bar>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import api from '../../api/homeApi.js';
import recordApi from '../../api/recordApi.js';
import otherApi from '../../api/otherApi.js';
import utils from '../../api/utils.js';
import bar from '../../components/tabBar.vue';
import homeHL from '../../static/img/homeHL.png';
import homeUN from '../../static/img/home.png';
import myHL from '../../static/img/userHL.png';
import myUN from '../../static/img/user.png';
import payHL from '../../static/img/iconPayHL.png';
import payUN from '../../static/img/iconPay.png';
import listHL from '../../static/img/iconListHL.png';
import listUN from '../../static/img/iconList.png';
import txImg from '../../static/img/avatarImg.jpeg';
import banner1 from '../../static/img/banner1.jpg';
import banner2 from '../../static/img/banner2.jpg';
import banner3 from '../../static/img/banner3.jpg';
import bwSwiper from '../../components/bw-swiper/bw-swiper.vue';

export default {
	data() {
		return {
			//swiperList: [{ img: banner1 }, { img: banner2 }, { img: banner3 }],
			indicatorDots: true,
			autoplay: true,
			interval: 2000,
			duration: 500,
			addressName: '',
			proclamationList: [],
			userId: '',
			userType: '',
			gurdianInfo: '',
			utils: utils,
			recordList: [],
			bannerList: [],
			txImg: txImg,
			tipNum: 0,
			avatar: '',
			tabList: [
				{
					name: 'Home',
					imgPL: homeHL,
					imgUN: homeUN,
					url: '../index/index'
				},
				{},
				{
					name: 'Mine',
					imgPL: myHL,
					imgUN: myUN,
					url: '../my/my'
				}
			],
			payObj: {
				name: 'Payment',
				imgPL: payHL,
				imgUN: payUN,
				url: '../bottomMenu/bottomMenu'
			},
			stuListObj: {
				name: 'Students',
				imgPL: listHL,
				imgUN: listUN,
				url: '../bottomMenu/bottomMenu'
			}
		};
	},
	components: { bar, bwSwiper },
	computed: mapState(['forcedLogin', 'hasLogin', 'userName', 'typeID']),
	methods: {
		// 跳转到访谈记录
		goRecord() {
			let _this = this;
			uni.navigateTo({
				url: `../record/recordList?userId=${_this.userId}`
			});
		},
		// 跳转到访谈查询
		goSearch() {
			uni.navigateTo({
				url: '../searchRecord/searchList'
			});
		},
		// 跳转到紧急电话
		goPhone() {
			uni.navigateTo({
				url: '../bottomMenu/emergencyPhone'
			});
		},
		// 监护人点击学生跳转访谈填写
		goWriteRecord(item) {
			uni.navigateTo({
				url: `../record/interviewRecord?intId=${item.interviewGuardianId}&stuId=${item.interviewStuId}`
			});
		},
		// 位置授权
		goLocation() {
			uni.navigateTo({
				url: '../locationAuthorization/locationAuthorization'
			});
		},

		goFeedback() {
			uni.navigateTo({
				url: '../feedback/feedback'
			});
		},

		// 进入公告列表页 
		goProList() {
			uni.navigateTo({
				url: '../proclamation/proList'
			});
		},

		// 进入公告详情
		goProDetails(id) {
			uni.navigateTo({
				url: `../proclamation/proContent?id=${id}`
			});
		}
	},
	onReady() {
		// if (data.body.gruSysUser.userType == '学生') {
		if ('iOS' == plus.os.name) {
			uni.getStorage({
				key: 'token',
				success: function(res) {
					// 如果token为空
					if (res.data) {
						var tokenStr = res.data;
						if (typeof tokenStr == 'undefined' || tokenStr == null || tokenStr == '') {
							//do nothing
						} else {
							uni.getStorage({
								key: 'userInfo',
								success: function(res) {
									if (res.data) {
										var userType = res.data.userType;

										var UserDefaultsClass = plus.ios.importClass('NSUserDefaults');
										var standardUserDefaults = UserDefaultsClass.standardUserDefaults();

										tokenStr = userType == '学生' ? tokenStr : '';

										plus.ios.invoke(standardUserDefaults, 'setObject:forKey:', tokenStr, 'token');
										plus.ios.invoke(standardUserDefaults, 'synchronize');
										console.warn('token is is is' + tokenStr);
									}
								},
								fail: function(err) {
									console.warn(err);
								}
							});
						}
					}
				},
				fail: function(err) {
					console.warn(err);
				}
			});
			// var UserDefaultsClass = plus.ios.importClass("NSUserDefaults");
			// var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
			// var tokenStr = RequestURL.token;
			// if(typeof tokenStr == "undefined" || tokenStr == null || tokenStr == "")
			// {
			// 	//do nothing
			// }
			// else{
			// 	var userType = RequestURL.userType;
			// 	if(userType == '学生')
			// 	{
			// 		plus.ios.invoke(standardUserDefaults, "setObject:forKey:",RequestURL.token, "token");
			// 		plus.ios.invoke(standardUserDefaults, "synchronize");
			// 		console.warn("token is is is"+RequestURL.token);
			// 	}
			// }
		}
		if ('Android' == plus.os.name) {
			uni.getStorage({
				key: 'token',
				success: function(res) {
					// 如果token为空
					if (res.data) {
						var tokenStr = res.data;
						if (typeof tokenStr == 'undefined' || tokenStr == null || tokenStr == '') {
							//do nothing
						} else {
							uni.getStorage({
								key: 'userInfo',
								success: function(res) {
									if (res.data) {
										var userType = res.data.userType;
										var main = plus.android.runtimeMainActivity(); //
										console.log('main main main is is is ' + main);
										var sp = plus.android.invoke(main, 'getSharedPreferences', 'com.student.preferences', 0);
										var editor = plus.android.invoke(sp, 'edit');

										tokenStr = userType == '学生' ? tokenStr : '';

										plus.android.invoke(editor, 'putString', 'token', tokenStr);
										plus.android.invoke(editor, 'commit');
										var token = plus.android.invoke(sp, 'getString', 'token', '');
										console.log('bbb token is is is ' + token);
									}
								},
								fail: function(err) {
									console.warn(err);
								}
							});
						}
					}
				},
				fail: function(err) {
					console.warn(err);
				}
			});

			// 			var main = plus.android.runtimeMainActivity();//
			//
			// 			console.log("main main main is is is "+main);
			// 			var sp =plus.android.invoke(main, "getSharedPreferences", "com.student.preferences", 0);
			//
			// 			var editor = plus.android.invoke(sp, "edit");
			// 			var tokenStr = RequestURL.token;
			//
			// 			if(typeof tokenStr == "undefined" || tokenStr == null || tokenStr == "")
			// 			{
			// 				//do nothing
			// 			}
			// 			else{
			// 				var userType = RequestURL.userType;
			// 				if(userType == '学生')
			// 				{
			// 					plus.android.invoke(editor, "putString", "token", tokenStr);
			// 					plus.android.invoke(editor, "commit");
			// 					var token = plus.android.invoke(sp, "getString", "token", "");
			// 					console.log("bbb token is is is "+token);
			// 				}
			// 			}
		}
		// }
	},
	async onShow() {
		let _this = this;
		let token = '';
		// 通过token判断是否为登录状态
		uni.getStorage({
			key: 'token',
			success: function(res) {
				// 如果token为空，跳转到登录页
				if (!res.data) {
					uni.redirectTo({
						url: '../login/login'
					});
				} else {
					token = res.data;
				}
			},
			fail: function(err) {
				console.log(err);
				// 如果获取token失败，跳转到登录页
				uni.redirectTo({
					url: '../login/login'
				});
			}
		});

		uni.getStorage({
			key: 'userInfo',
			success(res) {
				_this.userId = res.data.userId;
				_this.userType = res.data.userType;
				if (res.data.userType == '家长') {
					_this.tabList.splice(1, 1, _this.payObj);
				} else if (res.data.userType == '监护人') {
					_this.tabList.splice(1, 1, _this.stuListObj);
				}
			}
		});

		// 如果token为真的时候，请求首页需要加载的接口
		if (!!token) {
			let data = await api.getProclamation(token);
			let gurdianData = await api.getGurdianInfoByUserId(token);
			console.log("=========>>>>>>>>" + gurdianData.head.error_code);
			let getThemeTip = await api.getThemeNewCount(token);
			let bannerData = await api.getPictureByPictureType(token);
			let recordData = await recordApi.getInterviewRecordList(
				'interview/getGruSysInterviewList',
				{ current: 1, size: 100, interviewGuardianId: _this.userId, interviewStatus: '0' },
				token
			);
			if (gurdianData.head.error_code == 500 || recordData.head.error_code == 500 || getThemeTip.head.error_code == 500) {
				if (gurdianData.status == 500 || recordData.status == 500 || getThemeTip.status == 500)
				uni.removeStorage({
					key: 'token',
					success(res) {
						console.log(res, '>>>清除token缓存成功！');
					}
				});
				uni.removeStorage({
					key: 'userInfo',
					success(res) {
						console.log(res, '>>>清除个人信息缓存成功！');
					}
				});
				uni.removeStorage({
					key: 'locationInfo',
					success(res) {
						console.log(res, '>>>清除地理位置成功！');
					}
				});
				uni.removeStorage({
					key: 'guardianPhotoPath',
					success(res) {
						console.log(res, '>>>清除监护人头像成功！')
					}
				})
				uni.redirectTo({
					url: '../login/login'
				});
			}
			uni.showLoading({
				title: 'Please wait...',
				mask: true
			});
			// 公告信息
			if (data.head.status) {
				_this.proclamationList = data.body;
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
			// 访谈的学生信息
			if (recordData.head.status) {
				_this.recordList = recordData.body;
			} else {
				uni.showToast({
					title: recordData.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
			
						// 获取轮播数据
						console.log(bannerData, 112233)
						if (bannerData.head.status) {
							_this.bannerList = []
							bannerData.body.forEach(item => {
								_this.bannerList.push({
									img: _this.utils.localURL + '/' + item.picturePath.replace(/\\/g, '/')
								})
							})
							console.log(_this.bannerList)
						} else {
							uni.showToast({
								title: bannerData.head.msg,
								icon: 'none',
								duration: 2000
							});
						}
			
			// 首页的监护人信息
			if (gurdianData.head.status) {
				if (!!gurdianData.body.length) {
					_this.gurdianInfo = gurdianData.body[0];
					_this.avatar = gurdianData.body[0].guardianPhotoPath.replace(/\\/g, '/');
					uni.setStorage({
						key: 'guardianPhotoPath',
						data: gurdianData.body[0].guardianPhotoPath.replace(/\\/g, '/')
					})
				}
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
			// 首页主题反馈的未读标识
			if (getThemeTip.head.status) {
				_this.tipNum = getThemeTip.body;
				console.log(_this.tipNum);
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
			uni.hideLoading();

			uni.getSystemInfo({
				async success(res) {
					console.log(res);
					// 学生状态下登录，并且为安卓手机的情况下
					if (_this.userType == '学生' && res.platform == 'android') {
						uni.getLocation({
							type: 'wgs84',
							geocode: true,
							async success(res) {
								let Position = {};
								Position = {
									address: (
										res.address.country +
										res.address.province +
										res.address.city +
										res.address.district +
										res.address.street +
										res.address.streetNum
									).replace(/undefined/g, ''),
									latitude: res.latitude,
									longitude: res.longitude
								};
								let savePosition = await otherApi.savePosition('position/savePosition', Position, token);
							}
						});
						setInterval(async () => {
							let Position = {};
							uni.getLocation({
								type: 'wgs84',
								geocode: true,
								async success(res) {
									Position = {
										address: (
											res.address.country +
											res.address.province +
											res.address.city +
											res.address.district +
											res.address.street +
											res.address.streetNum
										).replace(/undefined/g, ''),
										latitude: res.latitude,
										longitude: res.longitude
									};
									await otherApi.savePosition('position/savePosition', Position, token);
								}
							});
						}, 900000);
					}
				}
			});
		}
	},
	onLoad() {
		let _this = this;
		
		//版本更新检查
		var notiClass = plus.ios.importClass("NSNotificationCenter");
		notiClass.defaultCenter().postNotificationNameobject("CheckUpdate","NULL");
		
		// 监听后台收到推送的点击消息事件
		plus.push.addEventListener(
			'click',
			function(msg) {
				var str = "";
				for(var k in msg){
					str += "key is "+k+": value is "+msg[k]+"\n";
				}
				console.warn("msg is "+str);
				
				if ('iOS' == plus.os.name) {
					uni.reLaunch({
						url: '../index/index',
						complete: function () {
							//根据payload传递过来的数据，打开一个详情
							var content = msg.content;
							console.warn('content is ======= ' + content);
							
							if (content) {
								// payload 按照规范是 Object，但实际推送过来有可能是 String，需要多一步处理；
								if(content.indexOf("位置信息") != -1){
									setTimeout(() => {
										uni.navigateTo({
											url: '../locationAuthorization/locationAuthorization'
										});
									}, 5000);
								}
								if(content.indexOf("消息反馈") != -1){
									setTimeout(() => {
										uni.navigateTo({
											url: '../feedback/feedback'
										});
									}, 5000);
								}
							}
						}
					});
				}
				// if ('Android' == plus.os.name) {
				// 	uni.showToast({
				// 		title: '点击了一条推送！',
				// 		duration: 1000
				// 	});
				// }
			},
			false
		);
		// 监听前台收到的在线消息事件
		plus.push.addEventListener(
			'receive',
			function(msg) {
				console.warn('msg is is is ======= ' + msg);
				if ('iOS' == plus.os.name) {
					uni.vibrateLong({
					    success: function () {
							let pages = getCurrentPages();
							let page = pages[pages.length - 1];
							
							if(page.route == "pages/feedback/feedbackContent"){
								Vue.prototype.$refreshPage();
							}
							else{
								//根据payload传递过来的数据，打开一个详情
								var payload = msg.payload;
								if (payload) {
									
									console.warn('payload is ======= ' + payload);
									// payload 按照规范是 Object，但实际推送过来有可能是 String，需要多一步处理；
									if (typeof payload === 'string') {
										payload = JSON.parse(payload);
										console.warn('payload string is ======= ' + payload);
									}
									if (typeof payload === 'object') {
										console.warn('bizType is ======= ' + payload.bizType);
										if(payload.bizType == '100'){
											uni.showToast({
												title: 'New Position',
												duration: 2000
											});
										}
										if(payload.bizType == '108'){
											uni.showToast({
												title: 'New Callback',
												duration: 2000
											});
										}
									}
								}
							}
					    }
					});
				}
			},
			false
		);
	}
};
</script>

<style scoped>
.content {
	padding: 0 !important;
}

.select_module {
	margin-top: 10px;
	display: flex;
	justify-content: space-between;
	background-color: #fff;
	padding: 15px 20px;
	box-sizing: border-box;
}

.select_module {
	text-align: center;
}

.select_option {
	flex: 1;
}

.select_module .option_tip {
	font-size: 14px;
	margin-top: 15px;
	color: #666;
	word-break: break-all;
}

.image_box {
	width: 60px;
	height: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	/* overflow: hidden; */
	background-color: #fbe5de;
	margin: auto;
}

.image_box .new_icon {
	width: 10px;
	height: 10px;
	line-height: 10px;
	text-align: center;
	background-color: #ff485d;
	border-radius: 10px;
	position: absolute;
	top: 8px;
	right: 0;
	z-index: 999;
	color: #fff;
	font-size: 12px;
}

.image_box image {
	width: 30px;
	height: 30px;
}

.guardian_message {
	background-color: #fff;
	padding: 15px 20px;
	margin-top: 10px;
}

.guardian_title {
	padding-bottom: 10px;
	border-bottom: solid 1px #f1f1f1;
	display: flex;
	align-items: center;
}

.guardian_title > text {
	font-size: 14px;
	color: #000;
}

.guardian_title .line {
	width: 2px;
	height: 14px;
	margin-right: 6px;
	background-color: #d82728;
}

.guardian_title .message_icon {
	margin-right: 5px;
}

.teacher_message {
	display: flex;
	align-items: center;
}

.teach_avatar {
	width: 75px;
	height: 75px;
	border-radius: 50%;
	margin-right: 15px;
}

.teacher_name {
	height: 25px;
	display: flex;
	align-items: center;
}

.teacher_name > text:first-child {
	color: #333;
	margin-right: 6px;
	font-size: 18px;
	white-space: nowrap;
}

.teacher_name > text:last-child {
	font-size: 10px;
	color: #999;
}

.teacher_tel {
	font-size: 12px;
	color: #999;
}

.today_message {
	background-color: #fff;
	padding: 15px 20px;
	margin-top: 10px;
}

.today_title {
	padding-bottom: 10px;
	border-bottom: solid 1px #f1f1f1;
	overflow: hidden;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.today_title .line {
	width: 2px;
	height: 14px;
	margin-right: 6px;
	background-color: #d82728;
}

.today_title > text:last-child {
	float: right;
	color: #d82728;
	font-size: 14px;
}

.today_title .message_icon {
	margin-right: 5px;
}

.today_list {
	list-style: none;
	padding: 0;
}

.today_item {
	padding: 10px 0;
	border-bottom: solid 1px #f1f1f1;
	color: #333;
	font-size: 14px;
	box-sizing: border-box;
}

.today_item > text {
	display: inline-block;
	vertical-align: middle;
}

.item_text {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	width: 290px;
}

.hello {
	display: flex;
	flex: 1;
	flex-direction: column;
}

.title {
	color: #8f8f94;
	margin-top: 50upx;
}

.ul {
	font-size: 30upx;
	color: #8f8f94;
	margin-top: 50upx;
}

.ul > view {
	line-height: 50upx;
}

.swiper_item {
	display: flex;
	align-items: center;
}

.swiper_item .item_name {
	color: #333;
	font-size: 16px;
}

.swiper_item .item_name view {
	padding: 5px 0;
	box-sizing: border-box;
}

.swiper_item .item_img {
	width: 75px;
	height: 75px;
	border-radius: 50%;
	margin-right: 15px;
}
</style>
